package org.niceHome.controller;

import com.github.pagehelper.PageInfo;
import org.niceHome.base.BaseController;
import org.niceHome.entity.Role;
import org.niceHome.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping(value = "/role")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;
    private final static String PAGE_INDEX = "role/index";
    private final static String PAGE_EDIT = "role/edit";
    private final static String PAGE_SUCCESS="common/successPage";

    private final static String PAGE_CREATE="role/create";
    private static final String LIST_ACTION ="redirect:/role";


    /**
     * 列表
     * @param model 请求域对象
     * @return 返回index页面
     * 更新实现分页功能
     */
    @RequestMapping
    public String index(Model model,@RequestParam Map<String, Object> filters){
        if (!filters.containsKey("pageNum")) {
            filters.put("pageNum", 1);
        }
        if (!filters.containsKey("pageSize")) {
            filters.put("pageSize", 10);
        }
        PageInfo<Role> page = roleService.findPage(filters);
        model.addAttribute("filters",filters);
        model.addAttribute("page",page);
        return PAGE_INDEX;
    }

    @GetMapping("/create")
    public String create() {
        return PAGE_CREATE;
    }

    @PostMapping("/save")
    public String save(Role role, Model model) {
        roleService.insert(role);
        return successPage(model,"新增角色成功");
    }

    @GetMapping("edit/{id}")
    public String edit(Model model, @PathVariable Long id){
        Role roleServiceById = roleService.getById(id);
        model.addAttribute("role",roleServiceById);
        return PAGE_EDIT;
    }

    @PostMapping(value="/update")
    public String update(Role role,Model model) {
        roleService.update(role);
        return successPage(model,"更新角色成功");
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Long id) {
        roleService.delete(id);
        return LIST_ACTION;
    }

}
